package com.web08.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author wzm
 * @create 2023-11-13 15:30
 * project_name:web2310
 * @Description
 */
//创建Servlet 模拟当访问该Servlet时会将数据同时浏览器保存起来 cookie
@WebServlet("/aServlet")
public class AServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建Cookie对象 利用构造方法设置key-value
       // Cookie cookie = new Cookie("username","zs");

        Cookie cookie = new Cookie("username","张三");

        //有的老版本的浏览器不能存储中文
        String name = "张三";
        //将中文进行URL编码
    /*    name = URLEncoder.encode(name,"UTF-8");
        System.out.println("存储的数据：" + name);
        //将编码后的数据存储到cookie
        Cookie cookie = new Cookie("username",name);*/




        //让Cookie活1周
        cookie.setMaxAge(7*24*60*60);



        //2.告诉浏览器 保存数据    利用set-cookie响应头保存数据
        resp.addCookie(cookie);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doPost(req, resp);
    }
}
